package algorithm;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Limiter {
    private int capacity; // 令牌桶容量
    private double rate; // 令牌发放速率
    private BlockingQueue<Object> queue; // 令牌队列

    public Limiter(int capacity, double rate) {
        this.capacity = capacity;
        this.rate = rate;
        this.queue = new ArrayBlockingQueue<>(capacity);

        // 初始化令牌桶
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep((long)(1000 / rate)); // 每隔一段时间往桶中放入令牌
                    queue.put(new Object());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public boolean allowRequest() {
        return queue.poll() != null; // 从令牌桶中获取一个令牌
    }

    // 测试
    public static void main(String[] args) {
        Limiter bucket = new Limiter(10, 2); // 令牌桶容量为10，令牌发放速率为2个/秒
        for (int i = 0; i < 20; i++) {
            if (bucket.allowRequest()) {
                System.out.println("Allow request " + (i + 1));
            } else {
                System.out.println("Reject request " + (i + 1));
            }
        }
    }
}

